package lv.rtu.ditf.dc.stream;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;

/**
 * 
 * @author Pāvels Koliškins, Edgars Matisāns
 *
 */
public class StringStreamReader {
	/**
	 * Reads string content from stream.
	 * @param inStream input stream containing string data
	 * @param encoding stream content encoding (not mandatory)
	 * @return string content
	 * @throws IOException if error occurs while reading content 
	 */
	public static String read(InputStream inStream, String encoding) throws IOException {
		Reader reader = null;
		if (encoding != null)
			try {
				reader = new InputStreamReader(inStream, encoding);
			}
			catch (UnsupportedEncodingException ex) {
				// TODO log
				ex.printStackTrace();
			}
		
		if (reader == null)
			reader = new InputStreamReader(inStream);
		BufferedReader buffReader = new BufferedReader(reader);
		
		StringBuilder content = new StringBuilder();
		String line;
		while ((line = buffReader.readLine()) != null) {
			content.append(line);
		}
		
		return content.toString();
	}
}
